import { Component, ChangeDetectionStrategy, OnInit, ChangeDetectorRef, Inject } from '@angular/core';
import { _HttpClient, SettingsService } from '@delon/theme';
import { NzNotificationService, UploadFile, NzMessageService, UploadXHRArgs } from 'ng-zorro-antd';
import { zip } from 'rxjs';
import { UserService, EmitterService, MSG_TYPE } from '@core';
import { HttpRequest, HttpClient, HttpEvent, HttpEventType, HttpResponse } from '@angular/common/http';
import { _HttpHeaders } from '@delon/theme/src/services/http/http.client';
import { TokenService, DA_SERVICE_TOKEN, ITokenService } from '@delon/auth';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { handleImg } from '@shared';

/**
 * 账号管理-基本资料
 */
@Component({
  selector: 'app-usrinfo-basic',
  templateUrl: './userinfo-basic.component.html',
  styleUrls: ['./userinfo-basic.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class UserInfoBasicComponent implements OnInit {
  constructor(
    public http: _HttpClient,
    private notice: NzNotificationService,
    private cdr: ChangeDetectorRef,
    private setting: SettingsService,
    private emit: EmitterService,
    private msg: NzMessageService,
    private sanitizer: DomSanitizer,
  ) {}

  avatar: SafeUrl = '';
  userLoading = true;
  user = null;

  ngOnInit(): void {
    this.http.get(`/cf/admin/user/${this.setting.user.userId}`).subscribe(res => {
      this.userLoading = false;
      this.user = res.data;
      this.avatar = './assets/img/avatar.jpg';
      if (res.data.avatar) {
        handleImg(this.http, this.sanitizer, res.data.avatar, (url: SafeUrl) => {
          this.avatar = url;
          this.cdr.detectChanges();
        });
      } else {
        this.cdr.detectChanges();
      }
    });
  }

  save() {
    const value = { ...this.user };
    this.http.put(`/cf/admin/user/edit`, value).subscribe(res => {
      if (res.status === 200) {
        this.notice.success('成功', '更新基本信息成功');
        this.setting.user.name = value.name;
        this.setting.user.avatar = value.avatar;
        this.emit.sendMessage({ type: MSG_TYPE.MODIFY_USERINFO });
      }
    });
    return false;
  }

  handleChange(ie: UploadFile) {
    if (ie.type === 'success') {
      this.getBase64(ie.file.originFileObj, (img: any) => {
        this.avatar = img;
        this.user.avatar = ie.file.response.data.fileName;
        this.cdr.detectChanges();
      });
    }
  }

  private getBase64(img: File, callback: (img: any) => void) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }

  beforeUpload = (file: File) => {
    const isJPG = file.type === 'image/jpeg';
    const isPNG = file.type === 'image/png';
    if (!isJPG && !isPNG) {
      this.msg.warning(`不支持的文件类型: ${file.type}`);
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      this.msg.warning('头像不能超过2MB');
    }
    return (isJPG || isPNG) && isLt2M;
  };
}
